# coding:utf-8
import json
import psycopg2
import time
import flask
import flask_cors


def get_config():
    file = "../../config.js"
    with open(file, 'r', encoding="utf-8") as f:
        str = f.read()
    index = str.index("{")
    config = json.loads(str[index:])
    return config

def get_cursor(config):
    conn = psycopg2.connect(database=config['db_database'], user=config['db_user'],
                            password=config['db_password'], host=config['db_host'], port=config['db_port'])
    cursor = conn.cursor()
    return conn,cursor

# ------------配置文件------------------
global_config = get_config()
conn = get_cursor(global_config)[0]
cursor = get_cursor(global_config)[1]

# -------------------------------------

from flask_cors import CORS
app = flask.Flask(__name__,template_folder="../../Car_WebContent")

# 右侧初始车辆
@app.route("/get_init_car/", methods=["GET", 'POST'])
def get_data_path():
    conn = get_cursor(global_config)[0]
    cursor = get_cursor(global_config)[1]
    sql = f'''SELECT * FROM car order by 车牌号 DESC limit 100; '''
    cursor.execute(sql)
    table = cursor.fetchall()
    conn.close
    return json.dumps(table)

# 车辆查询
@app.route('/get_search/<input>', methods=["GET", 'POST'])
def get_search(input):
    conn = get_cursor(global_config)[0]
    cursor = get_cursor(global_config)[1]
    sql = f'''SELECT 车牌号,型号 FROM car WHERE 车牌号 like '%{input}%' or 型号 like '%{input}%' '''
    index_like = sql.index('like')
    index_or = sql.index('or')
    danyin = []
    for i in sql[index_like:index_or]:
        if i == "'":
            danyin.append(i)
    if len(danyin) > 2:
        print("语法错误")
        print(sql)
    else:
        cursor.execute(sql)
        res = cursor.fetchall()
        if len(res) == 0:
            pass
        else:
            conn.close
            return json.dumps(res)

# 车辆弹窗
@app.route('/get_car_data/<input>', methods=["GET", 'POST'])
def get_car_data(input):
    conn = get_cursor(global_config)[0]
    cursor = get_cursor(global_config)[1]
    sql = f'''SELECT id,车牌号,型号,联系人,电话号码,所属单位,车辆类型,使用性质,车辆状况,备注,照片 FROM car WHERE 车牌号 = '{input}' '''
    cursor.execute(sql)
    res = cursor.fetchall()
    return json.dumps(res)

# 初始path
@app.route('/get_car_path/<input>', methods=["GET", 'POST'])
def get_path_data(input):
    conn = get_cursor(global_config)[0]
    cursor = get_cursor(global_config)[1]
    sql = f'''SELECT path FROM car WHERE 车牌号 = '{input}' '''
    cursor.execute(sql)
    res = cursor.fetchall()
    return json.dumps(res[0][0])

@app.route('/get_car_paths/<input>', methods=["GET", 'POST'])
def get_car_paths(input):
    translate = {1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '七', 8: '八', 9: '九',
                 10: '十', 11: '十一', 12: '十二', 13: '十三', 14: '十四', 15: '十五'}
    conn = get_cursor(global_config)[0]
    cursor = get_cursor(global_config)[1]
    index1 = input.index(",")
    index2 = input.index("月")
    car_id = input[:index1]
    day = input[index2+1:]
    if int(day) > 30:
        day = int(day) - 30
    if int(day) > 15:
        day = int(day) - 15
    col = translate[int(day)] + "号"
    sql = f'''SELECT {col} FROM car WHERE 车牌号 = '{car_id}' '''
    cursor.execute(sql)
    res = cursor.fetchall()
    list = eval(res[0][0])
    new_lis =[]
    for xy in list:
        new_lis.append(xy[0:2])
    return json.dumps(new_lis)

@app.route('/login', methods=['POST','GET'])
def login():
    data_dict = flask.request.form.to_dict()
    if data_dict['username'] == "admin" and data_dict['password'] == "123456":
        return "正确"
    else:
        return "错误"



def main():
    # 跨域
    time.sleep(2)
    flask_cors.CORS(app, supports_credentials=True)
    app.run(host='0.0.0.0', port=global_config["api_port_1"], debug=True)

if __name__ == '__main__':
    main()
    # get_data_path()

# 预显示100辆车辆
# http://192.168.6.50:8888/get_init_car

#车辆查询
# http://192.168.6.50:8888/get_search/川




